using System;
using System.Collections;
using System.Web;
using System.Web.UI.WebControls;
using System.IO;

using ECCIT.IO;

namespace ECCIT.Web
{
	/// <summary>
	/// 
	/// </summary>
	public class UploadedFile
	{
        public delegate string UploadFileRenameHandler(string fileName);

        public static ResultInfo Save(FileUpload fileUpload, DataItemPath filePath, UploadFileRenameHandler renameHandler)
        {
            if (fileUpload == null) throw new ArgumentNullException("fileUpload");
            if (filePath == null) throw new ArgumentNullException("filePath");

            ResultInfo result = new ResultInfo(false);
            try
            {
                if (fileUpload.PostedFile.ContentLength > 0)
                {
                    string path = filePath.PhysicalPath;
                    string fileName = (renameHandler == null) ? RenameHandlers.RenameToGuid(fileUpload.FileName) : renameHandler(fileUpload.FileName);
                    string fullFilePath = Path.Combine(path, fileName);
                    if (File.Exists(fullFilePath))
                        File.Delete(fullFilePath);
                    
                    fileUpload.SaveAs(fullFilePath);
                    result.Result = true;
                    result.ReturnObject = new FileInfo(fullFilePath);
                }
            }
            catch(Exception ex)
            {
                result.Message = string.Format("Error occurred in ECCIT.Web.UploadedFile.Save. Message: {0}", ex.Message);
                result.Exception = ex;
            }

            return result;
        }

        public static ResultInfo Save(HttpPostedFile postedFile, DataItemPath filePath, UploadFileRenameHandler renameHandler)
        {
            if (postedFile == null) throw new ArgumentNullException("postedFile");
            if (filePath == null) throw new ArgumentNullException("filePath");

            ResultInfo result = new ResultInfo(false);
            if (postedFile.ContentLength == 0) return result;

            string fileName = (renameHandler == null) ? RenameHandlers.RenameToGuid(postedFile.FileName) : renameHandler(postedFile.FileName);
            Stream fileDatastream = postedFile.InputStream;
            int contentLength = postedFile.ContentLength;
            string contentType = postedFile.ContentType;
            string resultMsg = string.Empty;

            byte[] fileContent = new byte[contentLength];
            int n = fileDatastream.Read(fileContent, 0, contentLength);

            FileStream pFileStream = null;
            try
            {
                string path = filePath.PhysicalPath;
                string fullFilePath = Path.Combine(path, fileName);
            
                pFileStream = new FileStream(fullFilePath, FileMode.OpenOrCreate);
                pFileStream.Write(fileContent, 0, contentLength);
                
                result.Result = true;
                result.ReturnObject = new FileInfo(fullFilePath);
            }
            catch (Exception ex)
            {
                result.Message = string.Format("Error occurred in ECCIT.Web.UploadedFile.Save. Message: {0}", ex.Message);
                result.Exception = ex;
            }
            finally
            {
                if (pFileStream != null)
                    pFileStream.Close();
            }

            return result;
        }

        public class RenameHandlers
        {
            public static string RenameToGuid(string fileName)
            {
                string name = Guid.NewGuid().ToString();
                string ext = fileName.Substring(fileName.LastIndexOf("."), fileName.Length - (fileName.LastIndexOf(".")));
                string renamedFileName = name + ext;
                return renamedFileName;
            }
        }
	}
}
